<template>
  <div class="marketingOrderDispatchStats-container">
    <!-- 查询 -->
    <div class="form-container">
      <div class="form color333">
        <div
          class="item flex-center flex-between"
          v-for="(item, index) in seachList"
          :key="index"
          :title="item.label"
          @click="handleShowPopup(item.model)"
        >
          <div class="label flex-s-0">{{ item.label }}：</div>
          <div class="select rel">{{ formText[item.model] }}</div>
          <img class="img" src="../../../../assets/imgs/reconsitution/statistics/jt_xl.png" alt="" />
        </div>
        <div class="blue flex-s-0" @click="handleSearch">查询</div>
      </div>

      <GdXceoAppBreadcrumb :orgCode="orgCode" @breadcrumbCallBack="handlebreadcrumbCallBack"></GdXceoAppBreadcrumb>
    </div>
    <div class="split"></div>
    <a-table
      size="small"
      bordered
      :columns="tableColumns"
      :data-source="tableData"
      :loading="tableLoading"
      :pagination="false"
      :scroll="{ x: 800, y }"
      :rowKey="(item, index) => index"
      class="table-container"
    >
      <template slot="name" slot-scope="value, record, rowIndex">
        <span
          class="blue"
          v-if="rowIndex > 0 && record.org_code && record.org_code.split('/').length <= level && !record.engineer_name"
          @click="handleSelectDepart(record)"
          >{{ getValue(record) }}
        </span>
        <span v-else>{{ getValue(record) }} </span>
      </template>
    </a-table>

    <van-popup v-model="showPopupdayId" position="bottom">
      <van-datetime-picker
        v-model="currentDate"
        type="date"
        title="请选择账期"
        @cancel="showPopupdayId = false"
        @confirm="handleSelectDayId"
        :maxDate="maxDate"
      />
    </van-popup>

    <van-popup v-model="showPopupstragetyName" position="bottom">
      <van-picker
        show-toolbar
        title="请选择策略名称"
        :columns="stragetyNameList"
        @confirm="handleSelectOptions($event, 'stragetyName')"
        @cancel="showPopupstragetyName = false"
      />
    </van-popup>

    <van-popup v-model="showPopupmarketingType" position="bottom">
      <van-picker
        show-toolbar
        title="请选择任务类型"
        :columns="marketTypeList"
        @confirm="handleSelectOptions($event, 'marketingType')"
        @cancel="showPopupmarketingType = false"
      />
    </van-popup>
  </div>
</template>

<script>
import GdXceoAppBreadcrumb from './components/breadcrumb.vue'
import Vue from 'vue'
import { USER_INFO } from '@/store/mutation-types'
import { parseResultAction } from '@/api/manage'
const _tableDataUrl = '2c3a07178ba92724018d30df2808006b',
  _personnelListUrl = '2c3a07178ba92724018d30df2808006b'
let _cacheTableDataList = []
export default {
  name: 'marketingOrderDispatchStats',
  components: { GdXceoAppBreadcrumb },
  data() {
    return {
      userDataPermission: {},
      maxOrgCodeLevel: 0,
      orgCode: '',
      marketTypeList: [],
      stragetyNameList: [],
      tableLoading: false,
      form: {
        marketingType: 'ALL',
        stragetyName: 'ALL',
        dayId: '',
      },
      tableData: [],
      level: 0,
      clickDepartNum: 0, // 点击 组织机构表格列，+1
      showPopupstragetyName: false,
      showPopupmarketingType: false,
      showPopupdayId: false,
      seachList: [
        { label: '账期', model: 'dayId' },
        { label: '策略名称', model: 'stragetyName' },
        { label: '任务类型', model: 'marketingType' },
      ],
      formText: {
        marketingType: '全部',
        stragetyName: '全部',
        dayId: '',
      },
      y: 600,
      maxDate: null,
      currentDate: new Date(),
      marketTypeList: [],
      children0: [],
      children1: [],
      keysList: [],
      marketType: [],
    }
  },

  computed: {
    lastOrgCodeArr() {
      let lastOrgCode = this.clickDepartNum ? this.orgCode : this.userDataPermission[0].orgCode
      return lastOrgCode.split('/')
    },
    tableColumns() {
      let result = [
        {
          title: '组织机构',
          dataIndex: 'depart_name',
          align: 'center',
          width: 200,
          scopedSlots: { customRender: 'name' },
        },
        {
          align: 'center',
          title: '当日新增',
          id: 0,
          children: this.children0,
        },
        {
          align: 'center',
          title: '累计到达',
          children: this.children1,
        },
      ]
      if (this.lastOrgCodeArr.length >= 5) {
        result[0].title = '姓名'
        result.splice(1, 0, {
          title: '岗位',
          dataIndex: 'engineer_type',
          align: 'center',
          width: 150,
          scopedSlots: { customRender: 'gw' },
        })
      }
      return result
    },
  },

  mounted() {
    const viewportHeight = window.innerHeight || document.documentElement.clientHeight
    this.y = viewportHeight - 320
  },

  created() {
    this.maxDate = new Date()
    this.handleSelectDayId()
    this.getMarketTypeList()

    const userInfo = Vue.ls.get(USER_INFO)
    this.userDataPermission = userInfo.datapermissionMap
    let maxOrgCode = ''
    for (const item of this.userDataPermission) {
      const { orgCode } = item
      !maxOrgCode && (maxOrgCode = orgCode)
      orgCode.split('/').length < maxOrgCode.split('/').length && (maxOrgCode = orgCode)
    }
    this.geMarketTypeList()
    this.getStragetNameList()
    this.maxOrgCodeLevel = maxOrgCode.split('/').length
    this.level = this.maxOrgCodeLevel == 5 ? 4 : 5
    this.maxOrgCodeLevel < 5 && ((this.orgCode = maxOrgCode), this.clickDepartNum++)
    this.handleSearch()
  },

  methods: {
    async getMarketTypeList() {
      const { result } = await parseResultAction('2c3a07178ba92724018d30e10bc1006c', { marketTypeList: '107' })
      this.marketType = result
      this.getTableColumnChildren()
    },
    filterDate(datestr) {
      if (!datestr) return ''
      const year = datestr.substring(0, 4)
      const month = datestr.substring(4, 6)
      const day = datestr.substring(6)
      const date = `${year}/${month}/${day}`
      return new Date(date)
    },
    getCurrentDate(datestr) {
      if (!datestr) return ''
      const year = datestr.substring(0, 4)
      const month = datestr.substring(4, 6)
      const day = datestr.substring(6)
      return `${year}-${month}-${day}`
    },
    async geMarketTypeList() {
      const { result } = await parseResultAction('2c3a07178ba92724018c00c520fa0028', {})
      this.marketTypeList =
        [{ text: '全部', code: 'ALL' }].concat(
          result.map(({ MARKETING_TYPE, MARKETING_NAME }) => {
            return {
              text: MARKETING_NAME,
              code: MARKETING_TYPE,
            }
          })
        ) || []
    },
    async getStragetNameList() {
      const { result } = await parseResultAction('2c3a07178ba92724018cee0cb92d0069', { timest: this.formText.dayId })
      this.stragetyNameList =
        [{ text: '全部', code: 'ALL' }].concat(
          result.map(({ STRAGETY_NAME }) => {
            return {
              text: STRAGETY_NAME,
              code: STRAGETY_NAME,
            }
          })
        ) || []
    },
    async getTableData() {
      const url = this.lastOrgCodeArr.length === 5 ? _personnelListUrl : _tableDataUrl
      this.tableLoading = true
      this.tableData = []
      const lastOrgId = this.orgCode.split('/')[this.orgCode.split('/').length - 1]
      const p1 = parseResultAction(url, {
        orgId: lastOrgId,
        ...this.form,
      })
      let p2 = Promise.resolve({ result: [] })
      if (!lastOrgId.includes('M')) {
        p2 = parseResultAction('2c3a07318d5479c8018d5479c8a20000', { orgId: lastOrgId })
      }
      // end 无数据也展示其他组织机构并且可以下钻 不需要直接注释上方代码
      Promise.all([p1, p2]).then((arr) => {
        this.tableLoading = false
        this.tableData = arr[0].result
        this.getAllKey(this.tableColumns)
        this.filterTableData(p2)
      })
    },
    filterTableData(list) {
      const obj = {}
      list.then(({ result }) => {
        const keyObj = {}
        this.keysList.forEach((item) => (keyObj[item] = 0))

        if (result.length && result[0].parent_id === 'root') {
          result.unshift({ depart_name: '广东省分公司', org_code: 'root' })
        }
        result.forEach((v) => {
          obj[v.depart_name] = {
            ...keyObj,
            ...v,
          }
        })
        this.tableData.forEach((v) => {
          obj[this.getValue(v)] = v
        })
        this.tableData = Object.keys(obj).map((key) => obj[key])
      })
    },
    getAllKey(arr = []) {
      arr.forEach((v) => {
        this.keysList.push(v.dataIndex)
        if (v.children) {
          this.getAllKey(v.children)
        }
      })
    },
    async getMutipleGridData() {
      this.tableData = []
      for (const item of this.userDataPermission) {
        const { orgCode } = item
        const orgId = orgCode.split('/')[orgCode.split('/').length - 1]
        const { result } = await parseResultAction(_tableDataUrl, {
          orgId,
          ...this.form,
        })
        _cacheTableDataList.push(record, result)
        this.tableData = _cacheTableDataList
      }
    },
    getValue(record) {
      return (
        record.depart_qname ||
        record.depart_cname ||
        record.depart_dname ||
        record.depart_sname ||
        record.engineer_name ||
        record.GRID_NAME ||
        record.depart_name
      )
    },
    handleSearch() {
      _cacheTableDataList = []
      this.maxOrgCodeLevel < 5 ? this.getTableData() : this.getMutipleGridData()
    },
    handleSelectDepart(record) {
      this.orgCode = record.org_code
      this.clickDepartNum++
      this.getTableData()
    },
    handlebreadcrumbCallBack({ orgCode, index }) {
      this.orgCode = orgCode
      this.clickDepartNum = index
      this.getTableData()
    },
    handleSelectOptions({ code, text }, type) {
      this.form[type] = code
      this.formText[type] = text
      type === 'marketingType' && this.getTableColumnChildren()
      this[`showPopup${type}`] = false
    },
    handleSelectDayId(val = new Date()) {
      let res = new Date(val).toLocaleDateString()
      res = res
        .split('/')
        .map((it) => it.padStart(2, '0'))
        .join('')
      this.form.dayId = res
      this.formText.dayId = this.getCurrentDate(res)
      this.showPopupdayId && (this.showPopupdayId = false)
      this.getStragetNameList()
    },
    handleShowPopup(type) {
      this[`showPopup${type}`] = true
    },
    getTableColumnChildren() {
      const type = this.form.marketingType || 'ALL',
        children0 = [],
        children1 = []
      this.marketType.forEach(({ MARKETING_TYPE, KPI_NAME, KPI_CODE, PID, order_number }) => {
        if (MARKETING_TYPE !== type) return
        const obj = {
          title: KPI_NAME,
          dataIndex: KPI_CODE.trim(),
          width: 96,
          align: 'center',
          order_number,
        }
        PID == 0 ? children0.push(obj) : children1.push(obj)
      })
      this.children0 = children0.sort((a, b) => {
        return a.order_number - b.order_number
      })
      this.children1 = children1.sort((a, b) => {
        return a.order_number - b.order_number
      })
    },
  },
}
</script>

<style lang="less" scoped>
@import '~@assets/less/reconsitution/common.less';

.marketingOrderDispatchStats-container {
  background: #fff;
  height: 100vh;

  .blue {
    color: #1890ff;
  }
  .form-container {
    margin-bottom: 2.1333vw;
    padding: 3.2vw 5.3333vw;
    .form {
      margin-bottom: 5.3333vw;
      display: grid;
      grid-template-columns: repeat(2, 1fr);
      gap: 3.2vw;
    }

    .item {
      .select {
        width: 21.3333vw;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        display: inline-block;
        .label {
          flex-shrink: 0;
        }
      }
    }
    .img {
      width: 3.7333vw;
      height: 3.7333vw;
    }
  }
  .split {
    width: 100%;
    height: 2.1333vw;
    background: #f3f7fa;
  }
  .table-container {
    margin: 2.1333vw;
  }
}
</style>